package com.xltq.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.EnumMap;
import java.util.Map;

public class ZxingUtils {
    public static ByteArrayOutputStream createQrCode(String qrcodeData) throws Exception {
        int white = 0x000000;
        int black = 0xFFFFFF;

        String characterSet = "utf-8";
        String imgFormat = "PNG";

        // 二维码宽度
        int qrcodeWidth = 256;
        // 二维码高度
        int qrcodeHeight = 256;

        // 生命二维码对象
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Map<EncodeHintType, Object> hint = new EnumMap(EncodeHintType.class);
        // 设置错误级别
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置字符编码
        hint.put(EncodeHintType.CHARACTER_SET, characterSet);
        // 设置边缘
        hint.put(EncodeHintType.MARGIN, 0);
        // 生成二维码
        BitMatrix bitMatrix = qrCodeWriter.encode(qrcodeData, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hint);
        int bitMatrixWidth = bitMatrix.getWidth();
        int bitMatrixHeight = bitMatrix.getHeight();
        BufferedImage qrcodeImg = new BufferedImage(bitMatrixWidth, bitMatrixHeight, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrixWidth; x++) {
            for (int y = 0; y < bitMatrixHeight; y++) {
                qrcodeImg.setRGB(x, y, bitMatrix.get(x, y) ? white : black);
            }
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(qrcodeImg, imgFormat, byteArrayOutputStream);
        return byteArrayOutputStream;
    }

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream qrCode = createQrCode("http://www.baidu.com");
        FileOutputStream fileOutputStream = new FileOutputStream("D:/1.png");
        fileOutputStream.write(qrCode.toByteArray());
    }
}
